package com.qili.core.quartz.CustomQuartz;

import cn.hutool.core.util.IdUtil;
import com.qili.core.utils.DictTypes;
import com.qili.entity.base.BaseDict;
import com.qili.entity.supervisor.ProjectNotice;
import com.qili.entity.supplier.SupplierProject;
import com.qili.entity.supplier.SupplierProjectAccept;
import com.qili.entity.supplier.dto.SupplierProjectAcceptDTO;
import com.qili.entity.supplier.dto.SupplierProjectDTO;
import com.qili.entity.sys.SysUser;
import com.qili.entity.sys.dto.SysUserDTO;
import com.qili.redis.RedisService;
import com.qili.service.SysUserService;
import com.qili.service.base.BaseCompanyService;
import com.qili.service.base.BaseDictService;
import com.qili.service.supervisor.ProjectNoticeServie;
import com.qili.service.supplier.SupplierProjectAcceptService;
import com.qili.service.supplier.SupplierProjectManagerService;
import com.qili.service.supplier.SupplierProjectPubNoticeService;
import com.qili.util.DateUtil;
import com.qili.util.StringUtil;
import lombok.extern.java.Log;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author zhaoyongke 内部项目-----X日内无人应接 -----------------每天执行一次
 * 情形1、X日内无人应接：实施费用比例增加Y，若依然无人应接，
 * 每日实施费用比例再增加Z，直到有人应接或者涨到最大值M或者招标截止时间为止。
 * 实施费用比例自动变更后，推送消息给发布人：您发布的XXX项目实施费用比例调整为35%+Y。
 * @date 2021/4/7
 * @description
 */
@Log
public class NbXDaysNoAcceptNoticeJob implements Job {
    @Autowired
    SysUserService sys;
    @Autowired
    private SupplierProjectPubNoticeService supplierProjectPubNoticeService;
    @Autowired
    private SupplierProjectManagerService supplierProjectManagerService;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    ProjectNoticeServie projectNoticeServie;
    @Autowired
    SupplierProjectAcceptService supplierProjectAcceptService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    BaseCompanyService baseCompanyService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("NbXDaysNoAcceptNoticeJob：启动任务=======================");
        run();
        System.out.println("NbXDaysNoAcceptNoticeJob：下次执行时间=====" +
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                        .format(context.getNextFireTime()) + "==============");
    }

    public void run() {

        log.info("NbXDaysNoAcceptNoticeJob=======开始==================================");
        String lockkey = "NbXDaysNoAcceptNoticeJob_key";
        String uuId = IdUtil.simpleUUID();
        try {
            lock(lockkey, uuId);
/*        X日内无人应接：实施费用比例增加Y，若依然无人应接，每日实施费用比例再增加Z，
        直到有人应接或者涨到最大值M或者招标截止时间为止。实施费用比例自动变更后，
        推送消息给发布人：您发布的XXX项目实施费用比例调整为35%+Y。*/
            saveSendXfZbjzRiqi();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            unlock(lockkey, uuId);
        }
    }

    /**
     * @param
     * @Author:zhaoyongke
     * @Description:设置X日后不响应则自动默认之前的费用 或X日后自动进行第二次比价，
     * @Date:16:09 2021/4/12
     */
    public void saveSendXfZbjzRiqi() {
        try {
            //内部项目---（涨到最大值M）
            List<BaseDict> typeListm = baseDictService.selectByTypeCode(DictTypes.NBM001.getType());
            //内部单位发布--x日无响应--修改实施费比例--（X日内无人应接）
            List<BaseDict> typeListx = baseDictService.selectByTypeCode(DictTypes.NX001.getType());
            //内部单位发布--x日无响应-（每日实施费用增加量z）
            List<BaseDict> typeListz = baseDictService.selectByTypeCode(DictTypes.NBZ001.getType());
            //内部单位发布--x日无响应-（每日实施费比例增加y）
            List<BaseDict> typeListy = baseDictService.selectByTypeCode(DictTypes.NBY001.getType());

            // X 值
//            String xvalue = "";
//            if (typeListx.size() > 0) {
//                BaseDict bzjbl = typeListx.get(0);
//                xvalue = bzjbl.getBadtLevel1();
//            }
//            BigDecimal decimal_x = new BigDecimal(xvalue);
            // m 值
            String mvalue = "";
            if (typeListx.size() > 0) {
                BaseDict bzjbl = typeListm.get(0);
                mvalue = bzjbl.getBadtLevel1();
            }
            BigDecimal decimal_m = new BigDecimal(mvalue);
            // z 值
            String zvalue = "";
            if (typeListx.size() > 0) {
                BaseDict bzjbl = typeListz.get(0);
                zvalue = bzjbl.getBadtLevel1();
            }
            BigDecimal decimal_z = new BigDecimal(zvalue);
            // y 值
            String yvalue = "";
            if (typeListx.size() > 0) {
                BaseDict bzjbl = typeListy.get(0);
                yvalue = bzjbl.getBadtLevel1();
            }
            BigDecimal decimal_y = new BigDecimal(yvalue);
            // 实施比例  系统配置的原来的实施费用比例
            String ssblper = "";
            List<BaseDict> typeListSsbl = baseDictService.selectByTypeCode(DictTypes.SSBL.getType());
            if (typeListSsbl.size() > 0) {
                BaseDict ssbl = typeListSsbl.get(0);
                ssblper = ssbl.getBadtLevel1();
            }
            BigDecimal decimal_ssbl = new BigDecimal(ssblper);
            // 查询无应接记录的数据  不到招标截止时间
            SupplierProjectDTO project = new SupplierProjectDTO();
            project.setStatus("006");
            project.setPublishType("001");// 0
            Date currdate = new Date();
            String currdateStr = DateUtil.formatDate(currdate, "yyyy-MM-dd HH:mm");
            String currdateStrss = DateUtil.formatDate(currdate, "yyyy-MM-dd");
            // 不到招标截止时间
            project.setZbEndDate(currdateStr);
            List<SupplierProjectDTO> list = supplierProjectManagerService.selectMyProjectListNotAccept(project);
            for (int i = 0; i < list.size(); i++) {
                SupplierProjectDTO dto = list.get(i);
                String zbEndDatestr = dto.getZbEndDate();
                Date zbEndDate = DateUtil.parseDate(zbEndDatestr, "yyyy-MM-dd HH:mm");
                System.out.println(11);
                //是否增加过比例
                String isAddFy = dto.getIsAddFy();
                if ("1".equals(isAddFy)) {
                    System.out.println(12);
                    // 每日实施费比例再增加z
                    // 发送通知
                    String ssbl = dto.getSsbl();
                    BigDecimal ssblnow = new BigDecimal(ssbl);
                    System.out.println(13);
                    // 不到指标截止时间
                    if (currdate.before(zbEndDate)) {
                        System.out.println(14);
                        BigDecimal ssbliabvlue = ssblnow.add(decimal_z);
                        dto.setSsbl(ssbliabvlue.stripTrailingZeros().toPlainString());
                        updateSSMoney(dto, ssbliabvlue);
                        BigDecimal aftertotalMoney = getSsTotalMoney(dto);
                        // 2021-05-15 修改为不能超过后台设置的最大比例
                        if (ssbliabvlue.compareTo(decimal_m) != 1) {
                            System.out.println(16);
                            //变更之后的 小于总费用的最大值 才更新 发通知
                            // 当天没有更新过
                            String ssblDate = dto.getSsblDate();
                            if (!currdateStrss.equals(ssblDate)) {
                                dto.setSsblDate(DateUtil.getCurrentDateString("yyyy-MM-dd"));
                                supplierProjectManagerService.updateByPrimaryKey(dto);
                                // 发送通知
                                sendNoticeToXf(dto, zvalue, ssbl);
                            }


                        }

                    }


                } else {
                    System.out.println(11);
                    // 获取项目的  x天 20210906 从项目表中天加了 字段
                    String xvalue = dto.getDays();
                    if (StringUtil.isNotBlank(xvalue)) {
                        // 实施费比例增加Y
                        Double x = Double.valueOf(xvalue) * 24;
                        int i2 = x.intValue();
                        Calendar calendar = new GregorianCalendar();
                        calendar.setTime(zbEndDate);
                        calendar.add(Calendar.HOUR, -i2);
                        /*招标截止是时间x天之前 */
                        Date datebeforex = new Date(calendar.getTimeInMillis());
                        if (currdate.after(datebeforex)) {
                            // 实施费比例增加Y
                            BigDecimal ssbliabvlue = decimal_ssbl.add(decimal_y);
                            dto.setSsbl(ssbliabvlue.stripTrailingZeros().toPlainString());
                            dto.setIsAddFy("1");
                            updateSSMoney(dto, ssbliabvlue);
                            BigDecimal aftertotalMoney = getSsTotalMoney(dto);
                            // 2021-05-15 修改为不能超过后台设置的最大比例
                            if (ssbliabvlue.compareTo(decimal_m) != 1) {
                                //变更之后的 小于总费用的最大值 才更新 发通知
                                dto.setSsblDate(DateUtil.getCurrentDateString("yyyy-MM-dd"));
                                supplierProjectManagerService.updateByPrimaryKey(dto);
                                // 发送通知
                                sendNoticeToXf(dto, yvalue, ssblper);
                            }

                        }
                    }

                }

            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }


    }

    /**
     * @param project
     * @param y
     * @param bl
     * @Author:zhaoyongke
     * @Description: 实施费用比例通知
     * @Date:15:45 2021/4/15
     */
    public void sendNoticeToXf(SupplierProject project, String y, String bl) throws Exception {
        Double yb = Double.valueOf(y) * 100;
        Double bib = Double.valueOf(bl) * 100;
        String yb_y = new BigDecimal(yb).stripTrailingZeros().toPlainString();
        String bib_bl = new BigDecimal(bib).stripTrailingZeros().toPlainString();
        ProjectNotice notice = new ProjectNotice();
        notice.setLinkId(project.getSupProjectId());
        notice.setIsView("0");
        notice.setSendTo(project.getCreateBy());
        notice.setTitle("您发布的" + project.getProjectName() + "项目实施费用比例调整为" + bib_bl + "%+" + yb_y + "%");
        notice.setNoticeType("109");//
        notice.setApplicantType("002");// 供需
        notice.setContent(project.getProjectName());
        notice.setCreateDate(DateUtil.getCurrentDateString());
        projectNoticeServie.insertSelective(notice);
    }

    /**
     * @param project
     * @Author:zhaoyongke
     * @Description: 获取项目的总实施费用
     * @Date:13:19 2021/4/15
     */
    public BigDecimal getSsTotalMoney(SupplierProjectDTO project) {
        BigDecimal jemoney = new BigDecimal("0.00");
        // 计算总money
        String publishType = project.getPublishType();
        String projectType = project.getProjectType();
        if ("001".equals(publishType)) {
            //正中发布的项目 计算实施费用总额
            if (projectType.indexOf("001") > -1) {
                String jlSsMoney = project.getJlSsMoney();
                BigDecimal money = new BigDecimal(jlSsMoney);
                jemoney = jemoney.add(money);

            }
            if (projectType.indexOf("002") > -1) {
                String zxSsMoney = project.getZxSsMoney();
                BigDecimal money = new BigDecimal(zxSsMoney);
                jemoney = jemoney.add(money);

            }
            if (projectType.indexOf("003") > -1) {
                String jcSsMoney = project.getJcSsMoney();
                BigDecimal money = new BigDecimal(jcSsMoney);
                jemoney = jemoney.add(money);

            }
            if (projectType.indexOf("project") > -1) {
                String qtSsMoney = project.getQtSsMoney();
                BigDecimal money = new BigDecimal(qtSsMoney);
                jemoney = jemoney.add(money);
            }

        }
        return jemoney;
   /*     String jestr = jemoney.stripTrailingZeros().toPlainString();
        return jestr;*/
    }

    /**
     * @param project
     * @param ssbliabvlue
     * @Author:zhaoyongke
     * @Description: 更新实施费用
     * @Date:13:38 2021/4/15
     */
    public void updateSSMoney(SupplierProjectDTO project, BigDecimal ssbliabvlue) throws Exception {
        // 计算总money
        String publishType = project.getPublishType();
        String projectType = project.getProjectType();
        if ("001".equals(publishType)) {
            //正中发布的项目 计算实施费用总额
            if (projectType.indexOf("001") > -1) {
                String jlFwMoney = project.getJlFwMoney();
                BigDecimal fwmoney = new BigDecimal(jlFwMoney);
                BigDecimal jlssMoney = fwmoney.multiply(ssbliabvlue);
                project.setJlSsMoney(jlssMoney.stripTrailingZeros().toPlainString());
            }
            if (projectType.indexOf("002") > -1) {
                String zxFwMoney = project.getZxFwMoney();
                BigDecimal fwmoney = new BigDecimal(zxFwMoney);
                BigDecimal zxssMoney = fwmoney.multiply(ssbliabvlue);
                project.setZxSsMoney(zxssMoney.stripTrailingZeros().toPlainString());

            }
            if (projectType.indexOf("003") > -1) {
                String jcFwMoney = project.getJcFwMoney();
                BigDecimal fwmoney = new BigDecimal(jcFwMoney);
                BigDecimal jcssMoney = fwmoney.multiply(ssbliabvlue);
                project.setJcSsMoney(jcssMoney.stripTrailingZeros().toPlainString());

            }
            if (projectType.indexOf("100") > -1) {
                String qtFwMoney = project.getQtFwMoney();
                BigDecimal fwmoney = new BigDecimal(qtFwMoney);
                BigDecimal qtssMoney = fwmoney.multiply(ssbliabvlue);
                project.setQtSsMoney(qtssMoney.stripTrailingZeros().toPlainString());
            }

        }

    }

    public void lock(String key, String uuId) {
        for (; ; ) {

            System.out.println(redisService);
            boolean r = stringRedisTemplate.opsForValue().setIfAbsent(key, uuId);
            stringRedisTemplate.expire(key, 600, TimeUnit.SECONDS);

            if (r) {
                return;
            } else {
                throw new RuntimeException("已经存在的执行程序...");
            }
        }
    }

    public void unlock(String key, String uuId) {
        if (uuId.equals(stringRedisTemplate.opsForValue().get(key))) {
            stringRedisTemplate.delete(key);
        }
    }

}
